<template>
  <div class="inputWraper">
    <input
      :type="type"
      :placeholder="placeholder"
      v-model="inputVal"
      :class="{ noValid: !isValid }"
      @blur="handelBlur"
    />
  </div>
</template>

<script>
export default {
  props: ["type", "placeholder", "rule", "errorMsg"],
  data() {
    return {
      inputVal: "",
      isValid: true,
    };
  },
  watch: {
    inputVal(newVal) {
      this.isValid = this.rule.test(newVal);
      if (!newVal) {
        this.isValid = true;
      }
      this.$emit("getVal", this.inputVal);
    },
  },
  methods: {
    handelBlur() {
      // bug: 用户名和密码都错误了后其中一个再次失去焦点会出现死循环
      if (!this.isValid) {
        // 使用轻提示后bug解决了
        this.$toast.fail(this.errorMsg);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.inputWraper {
  text-align: center;
  margin-bottom: 10 / 360 * 100vw;
  input {
    width: 80%;
    height: 30 / 360 * 100vw;
    border: 0;
    outline: none;
    border-bottom: 1px solid #333;
    &::-webkit-input-placeholder {
      font-size: 14 / 360 * 100vw;
    }
    &.noValid {
      border-color: red;
    }
  }
}
</style>
